package com.loveto.service;

import java.io.UnsupportedEncodingException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.loveto.common.JsonUtils;
import com.loveto.common.MyTouch;
import com.loveto.constant.LovetoConstant;


public class SetupMainActivity extends BaseActivity implements
View.OnClickListener, View.OnTouchListener {
	
	// 사용하는 변수들
	private Intent intentMoveToPage;
	private ProgressDialog progressDialog;
	private Handler myHandler = new Handler();
	private String memberid;
	private String gender;
	private String market;
	private int cntFriend;
	private int cntFollowing;
	private int newMessageCnt = 0;
	private int not_select_winner_tournamentID = 0;
	private int not_view_winner_tournamentID = 0;
	private String presentVersion;
	private String newestVersion;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.loveto_setup_main);
		
		//변수 초기화
		progressDialog = new ProgressDialog(this);
		
		//유저정보 받아오기
		SharedPreferences pref = getSharedPreferences("userInfo", Activity.MODE_PRIVATE);
		memberid = pref.getString("memberid", "김기용");
		gender = pref.getString("gender", "M");
		
		//클릭 리스너 달기
		((RelativeLayout)findViewById(R.id.area_explain_loveto)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_notice)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_list_friends)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_list_following)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_update)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_setup_alarm)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_setup_login)).setOnClickListener(this);
		((RelativeLayout)findViewById(R.id.area_bug_report)).setOnClickListener(this);
		((TextView)findViewById(R.id.goto_terms)).setOnClickListener(this);
		((TextView)findViewById(R.id.goto_policy)).setOnClickListener(this);
		
		// 터치 리스너 달기 // 버튼
		((RelativeLayout)findViewById(R.id.btn_footer01)).setOnTouchListener(this);
		((RelativeLayout)findViewById(R.id.btn_footer02)).setOnTouchListener(this);
		((RelativeLayout)findViewById(R.id.btn_footer03)).setOnTouchListener(this);
		((RelativeLayout)findViewById(R.id.btn_footer04)).setOnTouchListener(this);
		((RelativeLayout)findViewById(R.id.btn_footer05)).setOnTouchListener(this);
		
		if (isNetworkAvailableAndNotice()) {
			getPageInfo();
			getNewMessage();
		}
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.area_explain_loveto:
				intentMoveToPage = new Intent(SetupMainActivity.this,ExplainTournamentActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.area_notice:
				intentMoveToPage = new Intent(SetupMainActivity.this,SetupNoticeActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.area_bug_report:
				intentMoveToPage = new Intent(SetupMainActivity.this,SetupBugReportActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.area_list_friends:
				intentMoveToPage = new Intent(SetupMainActivity.this,FriendsListActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.area_list_following:
				intentMoveToPage = new Intent(SetupMainActivity.this,FollowingListActivity.class);
				startActivity(intentMoveToPage); 
				break;
			case R.id.area_update:
				break;
			case R.id.area_setup_alarm:
				intentMoveToPage = new Intent(SetupMainActivity.this,SetupAlarmActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.area_setup_login:
				intentMoveToPage = new Intent(SetupMainActivity.this,SetupLoginActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.goto_terms:
				intentMoveToPage = new Intent(SetupMainActivity.this,LoginInfoTermsActivity.class);
				startActivity(intentMoveToPage);
				break;
			case R.id.goto_policy:
				intentMoveToPage = new Intent(SetupMainActivity.this,LoginInfoPrivacyActivity.class);
				startActivity(intentMoveToPage);
				break;
		}
	}

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		switch (v.getId()) {
		case R.id.btn_footer01:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(LovotoMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer02:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(JoinedTournamentListActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer03:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(MessageMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer04:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(UserinfoViewMineActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		case R.id.btn_footer05:
			if (event.getAction() == MotionEvent.ACTION_DOWN){
				v.setBackgroundResource(R.drawable.btn_footer_touch);
			}
			else if (event.getAction() == MotionEvent.ACTION_UP){
				if (MyTouch.checkClick(v, event)) { //손을 땐 좌표로 클릭 여부 판단
					gotoActive(SetupMainActivity.class, v, R.drawable.btn_footer_unselected);
				} else {
					v.setBackgroundResource(R.drawable.btn_footer_unselected);
				}
			}
			break;
		}
		return true;
	}
	
	//화면 전환 시켜주기
	private void gotoActive(Class<?> class1,View v,int d) {
		intentMoveToPage = new Intent(SetupMainActivity.this,
				class1);
		startActivity(intentMoveToPage);
		v.setBackgroundResource(d);
	}
	
	private void getPageInfo() {
		
		//현재 버전 받아오기
		try {
			PackageInfo i = this.getPackageManager().getPackageInfo(
					this.getPackageName(), 0);
			presentVersion = i.versionName;
		} catch (NameNotFoundException e) { }
		Log.d("tag", "presentVersion:" + presentVersion);
		
		//현재 마켓 정보
		market = getResources().getString(R.string.app_market);
		Log.d("tag", "market:" + market);
		
		progressDialog.setMessage("정보를 불러오고 있습니다.");
		progressDialog.show();
		Runnable runnable = new Runnable(){
			@Override
			public void run() {
				//UI 를 건들기 때문에 핸들러 사용.
				Log.d("tag", "getPageInfo start");

				try {
					// 서버에 정보 보내기
					StringBuffer sb = new StringBuffer(
							LovetoConstant.SETUP_MAIN);
					sb.append("?memberid=").append(memberid);
					sb.append("&gender=").append(gender);
					sb.append("&market=").append(market);
					Log.d("tag", "url : " + sb.toString());
					String jsonText = JsonUtils.getStringFromUrl(sb.toString());
					Log.d("tag", "jsonText : " + jsonText);
					// JSONArray jsonArray = new JSONArray(jsonText);
					JSONObject object = new JSONObject(jsonText);

					cntFriend = object.getInt("cntFriend");
					cntFollowing = object.getInt("cntFollowing");
					newestVersion = object.getString("newestVersion");
					Log.d("tag", "cntFriend : " + cntFriend);
					Log.d("tag", "cntFollowing : " + cntFollowing);
					Log.d("tag", "newestVersion : " + newestVersion);

				} catch (JSONException e) {
					e.printStackTrace();
					Log.d("tag", "setRoundInfo() error, " + e.getMessage());
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "setRoundInfo() error, " + e.getMessage());
				} finally {
					// 화면 갱신
					myHandler.post(new Runnable() {
						@Override
						public void run() {

							((TextView) findViewById(R.id.text_friend_cnt))
									.setText("쪽지 친구 : " + cntFriend + "명");
							((TextView) findViewById(R.id.text_following_cnt))
									.setText("호감 이성 : " + cntFollowing + "명");
							((TextView) findViewById(R.id.text_version_present))
									.setText(presentVersion);
							((TextView) findViewById(R.id.text_version_newest))
									.setText(newestVersion);
							// 현재 버전과 최신 버전이 다를 때
							if (!presentVersion.equals(newestVersion)) {
								((TextView) findViewById(R.id.text_goto_update))
										.setVisibility(TextView.VISIBLE);
								((ImageView) findViewById(R.id.arrow_update))
										.setVisibility(ImageView.VISIBLE);
							}
							progressDialog.dismiss();
							Log.d("tag", "getPageInfo end");
						}
					});
				}
							
			}
		};
		new Thread(runnable).start();
	}
	
	private void getNewMessage() {
		
		//비로그인 시 실행하지 않음.
		if ("".equals(memberid)) {
			return;
		}
		
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				
				try {
					
					StringBuffer URL = new StringBuffer();
					URL.append(LovetoConstant.MESSAGE_CHECK_NEW_URL);
					URL.append("?memberid=").append(memberid);
					Log.d("tag", "URL: " + URL.toString());
					//서버에서 정보 받아오기
					String jsonText = JsonUtils.getStringFromUrl(URL.toString());
					Log.d("tag", "jsonText: " + jsonText);
					JSONObject getObject = new JSONObject(jsonText);
					newMessageCnt = getObject.getInt("new_cnt");
					Log.d("tag", "newMessageCnt: " + newMessageCnt);
					not_select_winner_tournamentID = getObject.getInt("not_select_winner_tournamentID");
					Log.d("tag", "not_select_winner_tournamentID: " + not_select_winner_tournamentID);
					not_view_winner_tournamentID = getObject.getInt("not_view_winner_tournamentID");
					Log.d("tag", "not_view_winner_tournamentID: " + not_view_winner_tournamentID);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} catch (JSONException e) {
					e.printStackTrace();
					Log.d("tag", "Get Json error : " + e.toString());
				} finally {
					// 풋터에 새 쪽지 개수 보여주기
					myHandler.post(new Runnable() {
						@Override
						public void run() {
							//풋터에 새로 받은 쪽지 개수 표시하기
							TextView vNewMsg = (TextView) findViewById(R.id.message_new_cnt);
							if (newMessageCnt !=0) {
								vNewMsg.setText("" + newMessageCnt);
								vNewMsg.setVisibility(TextView.VISIBLE);
							}
							if (not_select_winner_tournamentID != 0 || not_view_winner_tournamentID != 0) {
								showSimpleAlertForSelectOrViewWinner();
							}
						}
					});
				}
				Log.d("tag", "sendTalkMessage() end");
			}
		};
		new Thread(runnable).start();
	}

	private void showSimpleAlertForSelectOrViewWinner() {
		String title;
		String msg;
		if (not_select_winner_tournamentID != 0) {
			title = "토너먼트 주최완료!";
			msg = "주최 한 토너먼트의 마감시간이 완료되어 우승자를 결정해야합니다. 이동하시겠습니까?";
		} else {
			title = "우승자 결정완료!";
			msg = "참여 한 토너먼트의 우승자 결정이 완료되었습니다. 결과를 보기위해 이동하시겠습니까?";
		}
		new AlertDialog.Builder(this)
		.setTitle(title)
		.setMessage(msg)
		.setPositiveButton("이동", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				if (isNetworkAvailableAndNotice()) {
					dialog.dismiss();
					int gotoTournamentID = 0;
					if (not_select_winner_tournamentID != 0) {
						gotoTournamentID = not_select_winner_tournamentID;
					} else {
						gotoTournamentID = not_view_winner_tournamentID;
					}
					Intent intent = new Intent(SetupMainActivity.this, InfoTournamentActivity.class);
					intent.putExtra("tournamentID", "" + gotoTournamentID);
					startActivity(intent);
					
				}
			}
		})
		.setNegativeButton("취소", new DialogInterface.OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
			}
		}).show();
		
	}
	
}
